package com.mvvm.ktnet.base.activity

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.mvvm.ktnet.base.IBaseView
import com.mvvm.ktnet.base.viewmodel.BaseViewModel
import com.mvvm.ktnet.retention.ViewModelProviders
import me.hgj.jetpackmvvm.ext.getVmClazz


abstract class IBaseVmActivity<VM : BaseViewModel> : AppCompatActivity(), IBaseView {

    /**
     * 是否需要使用DataBinding 供子类BaseVmDbActivity修改，用户请慎动
     */
    private var isUserDb = false

    lateinit var mViewModel: VM

    abstract fun layoutId(): Int


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!isUserDb) {
            setContentView(layoutId())
        } else {
            initDataBind()
        }
        ViewModelProviders<BaseViewModel>()
        init(savedInstanceState)
        if (immersionBarEnabled()) initStatusBar()
    }

    override fun initStatusBar() {

    }

    override fun immersionBarEnabled(): Boolean = false

    private fun init(savedInstanceState: Bundle?) {
        mViewModel = createViewModel()
        registerUiChange()
        initView(savedInstanceState)
        createObserver()
        registorDefErrorChange()
        initLoad()
        initData()
    }

    override fun initDataBind() {

    }

    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(this).get(getVmClazz(this))
    }


    /**
     * 注册UI 事件
     */
    override fun registerUiChange() {
//        //显示弹窗
//        mViewModel.loadingChange.showDialog.observe(this, Observer {
//            showLoading()
//        })

    }

    /**
     * 将非该Activity绑定的ViewModel添加 loading回调 防止出现请求时不显示 loading 弹窗bug
     * @param viewModels Array<out BaseViewModel>
     */
    override fun addLoadingObserve(vararg viewModels: BaseViewModel) {
//        viewModels.forEach {viewModel ->
//            //显示弹窗
//            viewModel.loadingChange.showDialog.observe(this, Observer {
//                showLoading()
//            })
//        }
    }

    fun userDataBinding(isUserDb: Boolean) {
        this.isUserDb = isUserDb
    }

}